var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op

/* GET role info */
router.get('/', async function (req, res, next) {
    try {
        if (req.query.roleId) {
            var roleId = req.query.roleId
            var role = await models.Role.findOne({
                where: { [Op.and]: [{ id: `${roleId}` }] }
            })
            res.json({ role })
        } else {
            var roles = await models.Role.findAll()
            res.json({ roles })
        }
    } catch (e) {
        console.log(e);
    }
});

// 获取用户提交的信息并插入数据库
router.post('/', async function (req, res, next) {
    const { roleName } = JSON.parse(req.query.data)
    try {
        var role = await models.Role.create({
            roleName
        })
        res.json({ role })
    } catch (e) {
        console.log(e)
    }
})

// 修改角色信息
router.put('/:id', async function (req, res, next) {
    const id = req.params.id
    const { roleName } = JSON.parse(req.query.data)
    try {
        var role = await models.Role.update({
            roleName
        }, { where: { id } })

        res.json({ role })
    } catch (e) {
        console.log(e)
    }
})

// 删除角色信息
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id
    var role = await models.Role.findByPk(id)
    if (role) {
        role.destroy()
        res.json({ msg: '删除成功' })
    } else {
        res.json({ msg: '不存在该数据' })
    }
})

module.exports = router;
